package com.jet.rtdb.socket.client.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;


/**
 * @Author: zhangkaifeng.
 * @CreateTime: 2017/8/17 15:33
 * @Description:socket客户端
 */


public class RtdbClient {

    private int port;

    private String host;


    public RtdbClient(int port, String host) {
        this.port = port;
        this.host = host;
    }

    public void getConnect() {
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new MessageClientEncoder(), new RtdbClientHandler());
                }
            });

            // Start the client.
            ChannelFuture channelFuture = b.connect(host, port).sync();
            channelFuture.addListeners(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {

                }
            });
            // Wait until the connection is closed.
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                RtdbClient rtdbClient = new RtdbClient(8090, "192.168.1.206");
                rtdbClient.getConnect();
                RtdbClientHandler rtdbClientHandler = new RtdbClientHandler();
                rtdbClientHandler.getLastData();
            }
        });
        thread1.start();

//        Thread thread2 = new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(5000);
//                    Long l = System.currentTimeMillis();
//                    RtdbClientHandler rtdbClientHandler = new RtdbClientHandler();
//                    rtdbClientHandler.getLastData();
//                    System.out.println("耗时：" + (System.currentTimeMillis() - l));
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//        thread2.start();

    }


}
